package com.kzc.twelve.ui;

import android.util.Log;

import com.kzc.twelve.ApplicationHelper;
import com.kzc.twelve.Config;
import com.kzc.twelve.alg.AstarPathFinder;
import com.kzc.twelve.alg.Location;
import com.kzc.twelve.entity.Card;
import com.kzc.twelve.entity.Grade.OnScoreListener;

import java.util.List;

/**
 * 卡片选择监听器
 * Created by 柯尊诚 on 2015/12/10.
 * kzc
 */
public class CardSelectListener implements CardView.OnSelectListener{

    private GameCanvas canvas;
    private CardView[][] cards;

    private int[][] map = new int[Config.col][Config.row];
    private OnScoreListener listener;

    public CardSelectListener(GameCanvas canvas, CardView[][] cards, OnScoreListener listener) {
        this.canvas = canvas;
        this.cards = cards;
        this.listener = listener;
    }

    private CardView selectView;

    @Override
    public void onSelect(boolean isSelect, CardView view) {

        Log.d("xxx", String.format("on Click %s[%s,%s], %s", view.getNum(), view.getLat(), view.getLog(), isSelect));

        if (selectView == null) {
            if (isSelect && !view.isEmpty()) {
                selectView = view;
            } else {
                view.reset();
            }
        } else {
            CardView select = selectView;
            selectView = null;

            if (select == view && !isSelect) {
                return;
            }

            //检查是否可以合并
            List<Location> path = AstarPathFinder.findPath(new Location(select.getLog(), select.getLat()),
                    new Location(view.getLog(), view.getLat()),
                    toMap(select.getCard(), view.getCard()));

            Log.d("xxx", "path: " + path);
            //如果路径无效
            if (path.isEmpty()) {
                onMergeFailed(select, view);
                return;
            }

            //移动到空白处
            if (view.getNum() == 0) {

                Config.isCombine = false;

                setAnimation(select, view, path);
                //先移动再增加
                select.moveTo(view);
//                addRandomNum();

                checkGameOver();
                return;
            }

            //合并
            if (!view.canCombine(select)) {
                onMergeFailed(select, view);
            } else {
                //合并后要加分
                listener.rewards(view.getNum());

                Config.isCombine = true;

                //移动动画
                setAnimation(select, view, path);

                select.reset();
                view.combine(select);

            }

            checkGameOver();
        }
    }

    /**
     * 设置移动动画
     */
    private void setAnimation(CardView from, CardView to, List<Location> path) {
        canvas.animLayer.createMoveAnim(from, to, path);
    }


    /**
     * 判断游戏结束
     */
    private boolean checkGameOver() {
        int numCount = 0;
        for (int y = 0; y < Config.row; y++) {
            for (int x = 0; x < Config.col; x++) {
                //记录空的位置数量
                if (cards[x][y].getNum() == 0)
                    numCount++;
            }
        }
        //根据游戏规则，等级1移动到空白处+1，等级2移动到空白处+2，以此类推。
        //则判断游戏是否失败的条件就还有移动到空白处，是否有足够的位置可以生成随机卡片
        if (Config.level == Config.level_2){
            if (numCount < 2) {
                Config.INFO = "当前没有足够空位可以生成两张卡片！";
                Log.d("xxx","当前没有足够空位可以生成两张卡片！");
                canvas.endGame();
                return true;
            }
        } else if (Config.level == Config.level_3) {
            if (numCount < 3) {
                Config.INFO = "当前没有足够空位可以生成三张卡片！";
                Log.d("xxx","当前没有足够空位可以生成三张卡片！");
                canvas.endGame();
                return true;
            }
        }


        for (int y = 0; y < Config.row - 1; y++) {
            for (int x = 0; x < Config.col - 1; x++) {
                //当有空位，相邻有可以合并的卡片时，游戏继续
                if (cards[x][y].getNum() == 0 || cards[x][y].getNum() == cards[x + 1][y].getNum() || cards[x][y].getNum() == cards[x][y + 1].getNum()) {
                    Config.INFO = "当前没有空位且没有可合并对象！";
                    return false;
                }
            }
        }

        canvas.endGame();

        return true;
    }



    private int[][] toMap(Card start, Card end) {
        for (int y = 0; y < Config.row; y++) {
            for (int x = 0; x < Config.col; x++) {
                map[x][y] = cards[x][y].getNum() == 0 ? 1 : 0;
            }
        }

        map[start.getLat()][start.getLog()] = 1;
        map[end.getLat()][end.getLog()] = 1;

        return map;
    }

    /**
     * 路径无效，取消移动
     */
    private void onMergeFailed(CardView start, CardView end) {
        start.setSelect(false);
        start.refresh();
        end.setSelect(false);
        end.refresh();
        selectView = null;
        //当路径无效时震动
        ApplicationHelper.getHelper().getVibratorListener().onVibrator();
    }
}
